<template>
  <div class="app-container">
    <!--查询表单-->
    <el-form :inline="true" class="demo-form-inline">
      <!-- 所属课程 -->
      <el-form-item label="所属课程">
        <el-cascader
          v-model="selectedCourseId"
          placeholder="试试搜索：java"
          expand-trigger="hover"
          :options="courseList"
          :props="defaultProps"
          filterable
          @change="handleCourseChange">
        </el-cascader>
      </el-form-item>

      <!-- 所属章节 -->
      <el-form-item label="所属章节">
        <el-select v-model="searchObj.chapterId" placeholder="请选择章节" clearable>
          <el-option
            v-for="chapter in chapterList"
            :key="chapter.id"
            :label="chapter.title"
            :value="chapter.id">
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 题目类型 -->
      <el-form-item label="题目类型">
        <el-select v-model="searchObj.questionType" placeholder="请选择题目类型" clearable>
          <el-option
            v-for="item in questionTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 题目标题 -->
      <el-form-item>
        <el-input v-model="searchObj.title" placeholder="题目标题"/>
      </el-form-item>

      <el-button type="primary" icon="el-icon-search" @click="fetchData()">查询</el-button>
      <el-button type="default" @click="resetData()">清空</el-button>
    </el-form>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="数据加载中"
      border
      fit
      highlight-current-row>

      <el-table-column
        label="序号"
        width="70"
        align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column label="题目信息" width="300" align="center">
        <template slot-scope="scope">
          <div class="question-title">
            <span v-if="scope.row.questionType === 1">[单选题]</span>
            <span v-else-if="scope.row.questionType === 2">[多选题]</span>
            <span v-else-if="scope.row.questionType === 3">[判断题]</span>
            <span v-else-if="scope.row.questionType === 4">[填空题]</span>
            <span v-else>[简答题]</span>
            {{ scope.row.title }}
          </div>
        </template>
      </el-table-column>

      <el-table-column label="课程类别" width="150" align="center">
        <template slot-scope="scope">
          {{ getCourseTitle(scope.row.courseId) }}
        </template>
      </el-table-column>

      <el-table-column label="课程" width="150" align="center">
        <template slot-scope="scope">
          {{ getChapterTitle(scope.row.chapterId) }}
        </template>
      </el-table-column>

      <el-table-column label="难度" width="80" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.level === 1" type="success">简单</el-tag>
          <el-tag v-else-if="scope.row.level === 2" type="warning">一般</el-tag>
          <el-tag v-else type="danger">困难</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.gmtCreate.substr(0, 10) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <router-link :to="'/question/edit/'+scope.row.id">
            <el-button type="text" size="mini" icon="el-icon-edit">修改</el-button>
          </router-link>
          <el-button type="text" size="mini" icon="el-icon-delete" @click="removeDataById(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :current-page="page"
      :page-size="limit"
      :total="total"
      style="padding: 30px 0; text-align: center;"
      layout="total, prev, pager, next, jumper"
      @current-change="fetchData"
    />
  </div>
</template>

<script>
import questionApi from '@/api/edu/question'
import courseApi from '@/api/edu/course'
import subjectApi from '@/api/edu/subject'

export default {
  data() {
    return {
      listLoading: true, // 是否显示loading信息
      list: null, // 数据列表
      total: 0, // 总记录数
      page: 1, // 页码
      limit: 10, // 每页记录数
      searchObj: {
        courseId: '',
        chapterId: '',
        questionType: '',
        title: ''
      }, // 查询条件
      courseList: [], // 课程列表
      chapterList: [], // 章节列表
      selectedCourseId: '', // 选中的课程ID
      defaultProps: {
        children: 'children',
        label: 'title',
        value: 'id'
      },
      questionTypeOptions: [
        { value: 1, label: '单选题' },
        { value: 2, label: '多选题' },
        { value: 3, label: '判断题' },
        { value: 4, label: '填空题' },
        { value: 5, label: '简答题' }
      ]
    }
  },
  created() {
    // 当页面加载时获取数据
    this.fetchData()
    // 获取课程列表
    this.initCourseList()
  },
  methods: {
    // 获取分页带查询条件的列表
    fetchData(page = 1) {
      // 解决分页无效问题
      this.page = page
      this.listLoading = true
      questionApi.getPageList(this.page, this.limit, this.searchObj).then(response => {
        if (response.success === true) {
          this.list = response.data.rows
          this.total = response.data.total
        }
        this.listLoading = false
      })
    },
    
    // 初始化课程列表
    initCourseList() {
      subjectApi.getNestedTreeList().then(response => {
        this.courseList = response.data
      })
    },
    
    // 获取章节列表
    handleCourseChange(value) {
      if (value && value.length > 0) {
        // // 获取选中的课程分类ID
        // const selectedCourseId = value[value.length - 1]
        // this.searchObj.courseId = selectedCourseId
        // questionApi.getChapterListByCourseId(selectedCourseId).then(response => {
        //   this.chapterList = response.data.items
        // })

        // 获取课程列表以获取课程ID
        this.fetchCourseList(value)
      } else {
        this.searchObj.courseId = ''
        this.chapterList = []
      }
      this.searchObj.chapterId = ''
    },

      // 根据课程分类获取课程列表
      fetchCourseList(subjectIds) {
        const subjectParentId = subjectIds[0];
        const subjectId = subjectIds.length > 1 ? subjectIds[1] : '';
        
        // 使用最大整数值作为分页参数
        const maxIntValue = 2147483647;
        
        const searchParams = {
          subjectParentId: subjectParentId,
          subjectId: subjectId,
          title: '',
          teacherId: ''
        };
        
        courseApi.getPageList(1, maxIntValue, searchParams).then(response => {
          this.chapterList = response.data.rows;
        });
      },
    
    // 获取课程标题
    getCourseTitle(courseId) {
      // 遍历树形结构查找课程标题
      const findTitle = (list) => {
        for (let i = 0; i < list.length; i++) {
          const item = list[i]
          if (item.id === courseId) {
            return item.title
          }
          if (item.children && item.children.length > 0) {
            const title = findTitle(item.children)
            if (title) {
              return title
            }
          }
        }
        return null
      }
      return findTitle(this.courseList) || ''
    },
    
    // 获取章节标题
    getChapterTitle(chapterId) {
      for (let i = 0; i < this.chapterList.length; i++) {
        const chapter = this.chapterList[i]
        if (chapter.id === chapterId) {
          return chapter.title
        }
      }
      return ''
    },
    
    // 重置表单数据
    resetData() {
      this.searchObj = {
        courseId: '',
        chapterId: '',
        questionType: '',
        title: ''
      }
      this.chapterList = []
      this.fetchData()
    },
    
    // 删除题目
    removeDataById(id) {
      this.$confirm('此操作将永久删除该题目，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return questionApi.removeById(id)
      }).then(() => {
        this.fetchData()
        this.$message.success('删除成功')
      }).catch((response) => {
        if (response === 'cancel') {
          this.$message.info('已取消删除')
        }
      })
    }
  }
}
</script>

<style scoped>
.question-title {
  text-align: left;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>